package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.adapter.OrderAdapter;
import com.kingtone.rongji.biz.Order;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.BaseJsonHttpResponseHandler;

/**
 * @Author 李文辉
 * @Date 2015-6-10 上午9:15:07
 */
public class OrderListActivity extends BaseActivity
{

	private TextView title = null;
	private ImageView backBtn = null;
	private ImageView leftIcon = null;
	private TextView rightTitle = null;
	private RadioGroup radioGroup = null;
	private RadioButton radioOneMonthBtn = null;
	/** 存放数据的集合 */

	private ListView orderList = null;
	private OrderAdapter orderAdapter = null;

	private int flag = -1;
	private String rightTitleStr = null;// 右标题

	@Override
	protected void onCreate(Bundle paramBundle)
	{
		super.onCreate(paramBundle);
		this.mContext = this;
		this.setContentView(R.layout.activity_order_list);
		radioGroup = (RadioGroup) findViewById(R.id.order_radio_group);
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId)
			{

				String beginDate = RongJiUtils.getLastMonthDate();
				String endDate = RongJiUtils.getNextDayDate();
				if (checkedId == R.id.radio_one_month)
				{
					getOrderList(AppContasts.ORDER_TYPE_OK, AppContasts.ORDER_STATUS_ALL, true, beginDate, endDate); // 一月内订单
				} else if (checkedId == R.id.radio_more_one_month)
				{
					getOrderList(AppContasts.ORDER_TYPE_OK, AppContasts.ORDER_STATUS_ALL, true, null, beginDate); // 一月前订单
				} else if (checkedId == R.id.radio_cancel)
				{
					getOrderList(AppContasts.ORDER_TYPE_CANCELED, AppContasts.ORDER_STATUS_ALL, true, null, null);// 已取消订单
				}
			}

		});
		radioOneMonthBtn = (RadioButton) findViewById(R.id.radio_one_month);
		radioOneMonthBtn.setChecked(true);
		
	}

	private void initData()
	{
		flag = getIntent().getIntExtra("flag", 0);
		String beginDate = RongJiUtils.getLastMonthDate();
		String endDate = RongJiUtils.getNextDayDate();
		if (flag == AppContasts.ORDER_STATUS_WAITING_PAY)
		{
			// 待支付订单
			getOrderList(AppContasts.ORDER_TYPE_OK, AppContasts.ORDER_STATUS_WAITING_PAY, false, beginDate, endDate);
			rightTitleStr = getString(R.string.my_order_list_not_pay);

		} else if (flag == AppContasts.ORDER_STATUS_WAITING_RECEIVE)
		{
			// 待收货订单
			getOrderList(AppContasts.ORDER_TYPE_OK, AppContasts.ORDER_STATUS_WAITING_RECEIVE, false, beginDate, endDate);
			rightTitleStr = getString(R.string.my_order_list_not_receive);
		} else if (flag == AppContasts.ORDER_STATUS_ALL)
		{
		
			getOrderList(0, AppContasts.ORDER_STATUS_ALL, true,  beginDate, endDate);// 一月内所有订单
			rightTitleStr = getString(R.string.my_order_list);
		}
		else if (flag == AppContasts.ORDER_TYPE_CANCELED)
		{
			getOrderList(AppContasts.ORDER_TYPE_CANCELED, AppContasts.ORDER_STATUS_ALL, true, null, null);// 已取消订单
			rightTitleStr = getString(R.string.my_order_list);
			if(radioGroup != null)
			{
				RadioButton button = (RadioButton) radioGroup.getChildAt(2);
				button.setChecked(true);
			}
		}
	}

	private void setupView()
	{
		title = (TextView) findViewById(R.id.title);
		title.setText(getString(R.string.my_order_list));
		backBtn = (ImageView) findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				onBackPressed();
			}
		});

		leftIcon = (ImageView) findViewById(R.id.left_icon);
		leftIcon.setBackgroundResource(R.drawable.icon_zhang);

		rightTitle = (TextView) findViewById(R.id.right_title);
		rightTitle.setText(rightTitleStr);

		orderList = (ListView) findViewById(R.id.order_list);
	}

	/**
	 * 获取订单列表接口
	 * 
	 * @param orderType
	 * @param orderStatus
	 * @param isAll
	 */
	@SuppressWarnings("rawtypes")
	private void getOrderList(int orderType, int orderStatus, boolean isUserOldApi, String beginDate, String endDate)
	{
		HashMap<String, Object> params = new HashMap<String, Object>();
		Gson gson = new Gson();
		SharedPreferencesUtil instance = SharedPreferencesUtil.getInstance(mContext);
		String userId = instance.getString(AppContasts.USERID_KEY);
		params.put("InUser", userId);
		params.put("PageIndex", 0);
		params.put("PageSize", 500);
		params.put("OrderType", orderType);
		String url = "";
		if (isUserOldApi)
		{
			url = RongJiRestClient.API_GET_USER_RECENTLY_ORDER;
		} else
		{
			params.put("OrderStatus", orderStatus);
			url = RongJiRestClient.API_GET_NOT_RECEIVE_OR_NOT_PAY_ORDER;
		}
		if (!TextUtils.isEmpty(beginDate))
		{
			params.put("OrderBeginDate", beginDate);
		}
		if (!TextUtils.isEmpty(endDate))
		{
			params.put("OrderEndDate", endDate);
		}

		RongJiRestClient.getOrderList(mContext, gson.toJson(params), url, new BaseJsonHttpResponseHandler()
		{

			@Override
			public void onStart()
			{
				RongJiUtils.showEmptyProgress(mContext);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg2, String arg3, Object arg4)
			{
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int statusCode, Header[] arg1, String responseString, Object arg3)
			{
				RongJiUtils.dismissProgress();
				if (statusCode == HttpStatus.SC_OK)
				{
					if (responseString != null && !new String(responseString).equalsIgnoreCase("null"))
					{
						String result = new String(responseString);
						JSONObject obj = null;
						List<Order> list = new ArrayList<Order>();
						try
						{
							obj = new JSONObject(result);
							if (obj.has("Data"))
							{
								JSONArray pArray = obj.getJSONArray("Data");
								Gson gson = new Gson();
								JsonParser parser = new JsonParser();
								JsonElement element = parser.parse(pArray.toString());
								if (element instanceof JsonArray)
								{
									JsonArray array = element.getAsJsonArray();
									for (JsonElement myOrder : array)
									{
										Order object = gson.fromJson(myOrder, Order.class);
										list.add(object);
									}
								}
							}
						} catch (JSONException e)
						{

							e.printStackTrace();
						}
						orderAdapter = new OrderAdapter(list, mContext);
						orderList.setAdapter(orderAdapter);
					}
				}
			}

			@Override
			protected Object parseResponse(String arg0, boolean arg1) throws Throwable
			{
				return null;
			}
		});
	}

	@Override
	public void onResume()
	{
		setupView();
		initData();
		super.onResume();
	}
}
